"""
资源/菜单管理API
"""
from fastapi import APIRouter, HTTPException, status, Depends, Request
from typing import Optional, List
from models.m import Resource, OperationLog, AdminUser
from schemas.admin_schemas import (
    ResourceCreate, ResourceUpdate, ResourceResponse,
    ResponseModel
)
from utils.auth_middleware import get_current_user


resource_router = APIRouter(prefix="/admin/resources", tags=["资源管理"])


def build_tree(resources: List[Resource], pid: Optional[int] = None) -> List[dict]:
    """
    构建树形结构
    """
    tree = []
    for res in resources:
        if res.pid_id == pid:
            children = build_tree(resources, res.id)
            node = {
                "id": res.id,
                "name": res.name,
                "code": res.code,
                "type": res.type,
                "path": res.path,
                "icon": res.icon,
                "sort": res.sort,
                "status": res.status,
                "pid": res.pid_id,
                "create_time": res.create_time.isoformat(),
                "update_time": res.update_time.isoformat(),
                "children": children if children else []
            }
            tree.append(node)
    
    return sorted(tree, key=lambda x: x['sort'])


@resource_router.get("/tree", response_model=ResponseModel, summary="获取资源树")
async def get_resource_tree(
    type: Optional[int] = None,
    status: Optional[int] = None,
    current_user: AdminUser = Depends(get_current_user)
):
    """
    获取树形结构的资源列表
    """
    query = Resource.all()
    
    if type is not None:
        query = query.filter(type=type)
    
    if status is not None:
        query = query.filter(status=status)
    
    resources = await query.order_by('sort')
    
    # 构建树形结构
    tree = build_tree(list(resources))
    
    return {
        "code": 200,
        "message": "获取成功",
        "data": tree
    }


@resource_router.get("", response_model=ResponseModel, summary="获取资源列表（平铺）")
async def get_resources(
    page: int = 1,
    page_size: int = 100,
    type: Optional[int] = None,
    status: Optional[int] = None,
    current_user: AdminUser = Depends(get_current_user)
):
    """
    获取平铺的资源列表
    """
    query = Resource.all()
    
    if type is not None:
        query = query.filter(type=type)
    
    if status is not None:
        query = query.filter(status=status)
    
    total = await query.count()
    offset = (page - 1) * page_size
    resources = await query.offset(offset).limit(page_size).order_by('sort')
    
    items = []
    for res in resources:
        items.append({
            "id": res.id,
            "name": res.name,
            "code": res.code,
            "type": res.type,
            "path": res.path,
            "icon": res.icon,
            "sort": res.sort,
            "status": res.status,
            "pid": res.pid_id,
            "create_time": res.create_time.isoformat(),
            "update_time": res.update_time.isoformat(),
        })
    
    return {
        "code": 200,
        "message": "获取成功",
        "data": {
            "total": total,
            "page": page,
            "page_size": page_size,
            "items": items
        }
    }


@resource_router.get("/{resource_id}", response_model=ResponseModel, summary="获取资源详情")
async def get_resource(
    resource_id: int,
    current_user: AdminUser = Depends(get_current_user)
):
    """
    获取指定资源的详细信息
    """
    resource = await Resource.get_or_none(id=resource_id)
    
    if not resource:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="资源不存在")
    
    return {
        "code": 200,
        "message": "获取成功",
        "data": {
            "id": resource.id,
            "name": resource.name,
            "code": resource.code,
            "type": resource.type,
            "path": resource.path,
            "icon": resource.icon,
            "sort": resource.sort,
            "status": resource.status,
            "pid": resource.pid_id,
            "create_time": resource.create_time.isoformat(),
            "update_time": resource.update_time.isoformat(),
        }
    }


@resource_router.post("", response_model=ResponseModel, summary="创建资源")
async def create_resource(
    request: Request,
    resource_data: ResourceCreate,
    current_user: AdminUser = Depends(get_current_user)
):
    """
    创建新资源
    """
    # 检查资源代码是否已存在
    existing = await Resource.get_or_none(code=resource_data.code)
    if existing:
        raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="资源代码已存在")
    
    # 如果有父级，检查父级是否存在
    if resource_data.pid is not None:
        parent = await Resource.get_or_none(id=resource_data.pid)
        if not parent:
            raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="父级资源不存在")
    
    # 创建资源
    resource = await Resource.create(
        name=resource_data.name,
        code=resource_data.code,
        type=resource_data.type,
        path=resource_data.path,
        icon=resource_data.icon,
        sort=resource_data.sort,
        status=resource_data.status,
        pid_id=resource_data.pid
    )
    
    # 记录操作日志
    await OperationLog.create(
        user_id=current_user.id,
        action="create_resource",
        module="资源管理",
        description=f"创建资源: {resource.name}",
        ip=request.client.host,
        user_agent=request.headers.get("user-agent"),
        request_data=resource_data.model_dump(),
        status=1
    )
    
    return {
        "code": 200,
        "message": "创建成功",
        "data": {"id": resource.id}
    }


@resource_router.put("/{resource_id}", response_model=ResponseModel, summary="更新资源")
async def update_resource(
    request: Request,
    resource_id: int,
    resource_data: ResourceUpdate,
    current_user: AdminUser = Depends(get_current_user)
):
    """
    更新资源信息
    """
    resource = await Resource.get_or_none(id=resource_id)
    if not resource:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="资源不存在")
    
    # 更新字段
    if resource_data.name is not None:
        resource.name = resource_data.name
    if resource_data.type is not None:
        resource.type = resource_data.type
    if resource_data.path is not None:
        resource.path = resource_data.path
    if resource_data.icon is not None:
        resource.icon = resource_data.icon
    if resource_data.sort is not None:
        resource.sort = resource_data.sort
    if resource_data.status is not None:
        resource.status = resource_data.status
    if resource_data.pid is not None:
        # 不能将自己设置为自己的父级
        if resource_data.pid == resource_id:
            raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="不能将自己设置为父级")
        
        # 检查父级是否存在
        parent = await Resource.get_or_none(id=resource_data.pid)
        if not parent:
            raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="父级资源不存在")
        
        resource.pid_id = resource_data.pid
    
    await resource.save()
    
    # 记录操作日志
    await OperationLog.create(
        user_id=current_user.id,
        action="update_resource",
        module="资源管理",
        description=f"更新资源: {resource.name}",
        ip=request.client.host,
        user_agent=request.headers.get("user-agent"),
        request_data=resource_data.model_dump(exclude_none=True),
        status=1
    )
    
    return {
        "code": 200,
        "message": "更新成功",
        "data": None
    }


@resource_router.delete("/{resource_id}", response_model=ResponseModel, summary="删除资源")
async def delete_resource(
    request: Request,
    resource_id: int,
    current_user: AdminUser = Depends(get_current_user)
):
    """
    删除资源（同时删除子资源）
    """
    resource = await Resource.get_or_none(id=resource_id)
    if not resource:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="资源不存在")
    
    # 检查是否有子资源
    children_count = await Resource.filter(pid_id=resource_id).count()
    if children_count > 0:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail=f"该资源下还有 {children_count} 个子资源，请先删除子资源"
        )
    
    # 删除资源
    await resource.delete()
    
    # 记录操作日志
    await OperationLog.create(
        user_id=current_user.id,
        action="delete_resource",
        module="资源管理",
        description=f"删除资源: {resource.name}",
        ip=request.client.host,
        user_agent=request.headers.get("user-agent"),
        status=1
    )
    
    return {
        "code": 200,
        "message": "删除成功",
        "data": None
    }

